package org.spruice.proxy;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * User: mrettig
 * Date: Feb 8, 2009
 * Time: 12:40:36 PM
 */
public class BeanCallback implements MethodInterceptor {

    private String name;
    private MethodInterceptor target;

    public BeanCallback(String name, MethodInterceptor target) {
        this.name = name;
        this.target = target;
    }

    public String getName() {
        return name;
    }

    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        if (isValid(method, args)) {
            return target.intercept(obj, method, args, proxy);
        }
        return null;
    }

    private boolean isValid(Method method, Object[] args) {
        if (method.getName().equals("finalize")) {
            if (args == null || args.length == 0) {
                return false;
            }
        }
        return true;
    }


    public static void invoke(Object instance, Method m) {
        if (!m.isAccessible()) {
            m.setAccessible(true);
        }
        try {
            m.invoke(instance);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
}
